package com.love.cloud.auth.service.impl;

import cn.hutool.extra.servlet.ServletUtil;
import com.love.cloud.auth.service.LoginAttemptService;
import com.love.cloud.common.core.constant.CacheConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 登陆失败次数记录
 * @author hongdongqu
 */
@Service
public class LoginAttemptServiceImpl implements LoginAttemptService {
    /**
     * 时间间隔（分钟）
     */
    private static final int TIME_INTERVAL = 10;
    /**
     * 登录失败重试次数上限
     */
    private static final int FAILED_RETRY_TIMES = 5;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private HttpServletRequest request;

    @Override
    public void loginSucceeded(String key) {
        String clientIP = ServletUtil.getClientIP(request);
        String countKey = CacheConstants.USER_LOGIN_FAILED_COUNT + clientIP+":"+key;
        //删除key
        stringRedisTemplate.delete(countKey);
    }
    @Override
    public void loginFailed(String key) {
        String clientIP = ServletUtil.getClientIP(request);
        String countKey = CacheConstants.USER_LOGIN_FAILED_COUNT +clientIP+":"+ key;
        RedisAtomicInteger counter = getRedisCounter(countKey);
        // 失败次数 + 1
        counter.getAndIncrement();
    }
    @Override
    public boolean isLocked(String key) {
        String clientIP = ServletUtil.getClientIP(request);
        String countKey = CacheConstants.USER_LOGIN_FAILED_COUNT + clientIP+":"+key;
        RedisAtomicInteger counter = getRedisCounter(countKey);
        if (counter.get() >= FAILED_RETRY_TIMES) {
            return false;
        }
        return true;
    }

    /**
     * 根据key获取计数器
     *
     * @param key key
     * @return
     */
    private RedisAtomicInteger getRedisCounter(String key) {
        RedisAtomicInteger counter =
                new RedisAtomicInteger(key, stringRedisTemplate.getConnectionFactory());
        if (counter.get() == 0) {
            // 设置过期时间
            counter.expire(TIME_INTERVAL, TimeUnit.MINUTES);
        }
        return counter;
    }

    @Override
    public String getErrorMessage(String key) {
        return "";
    }
}
